<template>
  <el-container class="register-container">
    <el-main>
      <el-card class="register-card">
        <template #header>
          <div class="card-header">
            <h2>用户注册</h2>
          </div>
        </template>
        <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          label-width="100px"
          @submit.prevent="handleRegister"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="registerForm.username"
              placeholder="请输入用户名 (3-50字符)"
              clearable
            />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="registerForm.email"
              placeholder="请输入邮箱"
              clearable
            />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码 (8-30字符)"
              show-password
              clearable
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="password_confirmation">
            <el-input
              v-model="registerForm.password_confirmation"
              type="password"
              placeholder="请再次输入密码"
              show-password
              clearable
            />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input
              v-model="registerForm.nickname"
              placeholder="请输入昵称 (可选)"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" native-type="submit" :loading="loading">
              注册
            </el-button>
            <el-button @click="goToLogin">已有账户？去登录</el-button>
          </el-form-item>
        </el-form>
        <div v-if="error" class="error-message">
          <el-alert :title="error" type="error" show-icon :closable="false" />
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import authService from '../api/auth.service';
import { ElMessage } from 'element-plus';

const router = useRouter();

const registerFormRef = ref(null);
const registerForm = ref({
  username: '',
  email: '',
  password: '',
  password_confirmation: '',
  nickname: '',
});
const loading = ref(false);
const error = ref(null);

// 自定义密码确认校验规则
const validatePassConfirm = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== registerForm.value.password) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度在 3 到 50 个字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 30, message: '密码长度在 8 到 30 个字符', trigger: 'blur' },
    // 更多密码强度规则可以根据后端要求添加
  ],
  password_confirmation: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePassConfirm, trigger: 'blur' },
  ],
  nickname: [
    { min: 1, max: 50, message: '昵称长度在 1 到 50 个字符', trigger: 'blur' },
  ],
};

const handleRegister = async () => {
  if (!registerFormRef.value) return;
  registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      error.value = null;
      try {
        const response = await authService.register(registerForm.value);
        // 假设注册成功后，后端返回的数据包含 access_token 和用户信息
        localStorage.setItem('user_token', response.data.access_token);
        // 可选：存储用户信息
        // localStorage.setItem('user_info', JSON.stringify(response.data.user));

        ElMessage.success(response.message || '注册成功！将跳转到首页。');
        router.push({ name: 'Home' }); // 注册成功后跳转到首页
      } catch (err) {
        console.error('注册失败:', err);
        error.value = err.message || '注册失败，请检查您输入的信息或网络连接';
        if (err.errors) {
          let fieldErrors = [];
          for (const key in err.errors) {
            fieldErrors.push(...err.errors[key]);
          }
          error.value = fieldErrors.join('; ');
        }
        ElMessage.error(error.value);
      } finally {
        loading.value = false;
      }
    }
  });
};

const goToLogin = () => {
  router.push({ name: 'Login' });
};

</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 100px); /* 减去导航栏等高度 */
  background-color: #f0f2f5;
  padding: 20px 0;
}

.register-card {
  width: 450px;
}

.card-header h2 {
  margin: 0;
  text-align: center;
}

.error-message {
  margin-top: 15px;
}
</style> 